/**
 * request 接口请求
 */
import * as appConfig from '@/config/config'
import * as base from '@/common/sju.base.js'
import * as nav from '@/common/sju.nav.js'
import * as alert from '@/common/sju.alert.js'
import * as login from '@/common/sju.login.js'

/**
 * @description request 网络请求
 * @param {string} url 请求的地址
 * @param {string} method 请求类型
 * @param {object} data 请求参数
 * @param {function} success 成功后回调的方法
 * @param {function} fail 失败后回调的方法
 * @param {bool} showLoading 是否显示加载框(默认false)
 * @param {string} contentType 内容类型(默认application/x-www-form-urlencoded 表单默认的提交数据的格式）)
*/

function request(url, method, data, showLoading, contentType){
	if (base.isNull(showLoading))
		showLoading = false
	if (base.isNull(contentType))
		contentType = 'application/x-www-form-urlencoded'
	if (showLoading == true)
		alert.showLoading()
	return new Promise((resolve, reject) => {
		uni.request({
			method: method || 'get',
			timeout: appConfig.timeout,
			url: appConfig.apiUrl + url,
			data: data,
			header: {
				'content-type':contentType,
				'Authorization': 'Bearer ' + login.getValue('token')
			}
		}).then(response => {
			if (showLoading == true)
				uni.hideLoading()
			let { error, res } = response
			if (error) {
				alert.showInfo('后端接口连接异常')
				reject('后端接口连接异常')
				return
			}
			const code = response.data.code || 200
			const msg = response.data.message
			if (code === 401) {
				alert.showConfirmPromise('登录状态已过期，您可以继续留在该页面，或者重新登录?').then(res => {
					if (res.confirm) {
						reject('无效的会话，或者会话已过期，请重新登录。')
						nav.redirectTo('/intake/login')
					}
				})
			} else if (code === 500) {
				alert.showInfo(msg)
				reject('500')
			} else if (code !== 200) {
				alert.showInfo(msg)
				reject(code)
			}
			resolve(response.data)
		}).catch(error => {
			if (showLoading == true)
				uni.hideLoading()
			let { message } = error
			if (message === 'Network Error') {
				message = '后端接口连接异常'
			} else if (message.includes('timeout')) {
				message = '系统接口请求超时'
			} else if (message.includes('Request failed with status code')) {
				message = '系统接口' + message.substr(message.length - 3) + '异常'
			}
			alert.showInfo(message)
			reject(error)
		})
	})
}

export { request }
